package com.crm.miaohe.controller.erp;

import com.crm.miaohe.common.ApplicationConstant;
import com.crm.miaohe.controller.erp.response.*;
import com.crm.miaohe.exception.ErpBusinessException;
import com.crm.miaohe.utils.CustomK3CloudApi;
import com.kingdee.bos.webapi.sdk.K3CloudApi;
import com.kingdee.bos.webapi.sdk.QueryParam;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@RequestMapping("/api/erp/common")
public class ErpCommonController {

    private final CustomK3CloudApi api;

    public ErpCommonController(CustomK3CloudApi api) {
        this.api = api;
    }

    /**
     * 客户组织
     *
     * @return
     */
    @GetMapping("/organization")
    public ResponseEntity<List<CustomerGroup>> getOrganization() {
        List<CustomerGroup> datas = null;

        try {
            datas = api.executeBillQuery(new QueryParam()
                            .setFormId("ORG_ORGANIZATIONS")  //ORG_ORGANIZATIONS  组织表
                            .setFieldKeys("FName,FDOCUMENTSTATUS,FORGID,FNUMBER")
                            .setFilterString("FDOCUMENTSTATUS = 'C' AND FFORBIDSTATUS = 'A'"), //C 代表已经审核 A代表未禁用
                    CustomerGroup.class);
            return ResponseEntity.ok(datas);
        } catch (Exception e) {
            throw new ErpBusinessException(HttpStatus.BAD_REQUEST, ApplicationConstant.KINGDEE_001, e.getMessage());
        }
    }

    /**
     * 客户部门
     *
     * @return
     */
    @GetMapping("/dept")
    public ResponseEntity<List<CustomerGroup>> getDept() {
        List<CustomerGroup> datas = null;

        try {
            System.out.println(api.toString());
        	datas = api.executeBillQuery(new QueryParam()
                            .setFormId("BD_Department")  // 部门
                            .setFieldKeys("FName,FNumber")
                            .setFilterString("FDOCUMENTSTATUS = 'C' AND FFORBIDSTATUS = 'A'"), //C 代表已经审核 A代表未禁用
                    CustomerGroup.class);
            return ResponseEntity.ok(datas);
        } catch (Exception e) {
        	e.printStackTrace();
            throw new ErpBusinessException(HttpStatus.BAD_REQUEST, ApplicationConstant.KINGDEE_001, e.getMessage());
        }
    }

    /**
     * 客户最小分类
     *
     * @return
     */
    @GetMapping("/customerLastType")
    public ResponseEntity<List<CustomerGroup>> getCustomerLastType() {

        try {
            List<CustomerGroup> datas = api.executeBillQuery(new QueryParam()
                            .setFormId("AMB_CustomerGroup")
                            .setFieldKeys("FID,FName,FNUMBER,FPARENTID"), //C 代表已经审核 A代表未禁用, //父分类为0
                    CustomerGroup.class);
            Map<String, String> idMap = new HashMap<>();
            List<CustomerGroup> leafs = new ArrayList<>();
            for(CustomerGroup g: datas) {
                if (!idMap.containsKey(g.getFNUMBER())) {
                    leafs.add(g);
                    idMap.put(g.getFNUMBER(), "");
                }
            }
            leafs.sort(Comparator.comparing(CustomerGroup::getFNUMBER));
            return ResponseEntity.ok(leafs);
        } catch (Exception e) {
            throw new ErpBusinessException(HttpStatus.BAD_REQUEST, ApplicationConstant.KINGDEE_001, e.getMessage());
        }
    }

    /**
     * 客户大分类
     *
     * @return
     */
    @GetMapping("/customerType")
    public ResponseEntity<List<CustomerGroup>> getCustomerType() {
        List<CustomerGroup> datas = null;

        try {
            datas = api.executeBillQuery(new QueryParam()
                            .setFormId("AMB_CustomerGrouP")
                            .setFieldKeys("FID,FName,FNUMBER,FPARENTID")
                            .setFilterString("FPARENTID = 0 "), //父分类为0
                    CustomerGroup.class);
            return ResponseEntity.ok(datas);
        } catch (Exception e) {
            throw new ErpBusinessException(HttpStatus.BAD_REQUEST, ApplicationConstant.KINGDEE_001, e.getMessage());
        }
    }

    /**
     * 客户小分类
     *
     * @return
     */
    @GetMapping("/customerChildrenType/{parentId}")
    public ResponseEntity<List<CustomerGroup>> getCustomerChildrenType(@PathVariable String parentId) {
        List<CustomerGroup> datas = null;
        try {
            datas = api.executeBillQuery(new QueryParam()
                            .setFormId("AMB_CustomerGrouP")
                            .setFieldKeys("FID,FName,FNUMBER,FPARENTID")
                            .setFilterString("FPARENTID = '" + parentId + "' "),
                    CustomerGroup.class);
            return ResponseEntity.ok(datas);
        } catch (Exception e) {
            throw new ErpBusinessException(HttpStatus.BAD_REQUEST, ApplicationConstant.KINGDEE_001, e.getMessage());
        }
    }

    /**
     * 业务员
     *
     * @return
     */
    @GetMapping(value = {"/biz", "/biz/{dept}"})
    public ResponseEntity<List<Sales>> getBiz(@PathVariable(required = false) String dept) {
        List<Sales> datas = null;
        try {

            QueryParam queryParam = new QueryParam().setFormId("BD_OPerator")
                    .setFieldKeys("FOperatorType,FName,FNumber");
            if (StringUtils.hasLength(dept)) {
                queryParam = queryParam.setFilterString("FBizOrgId.FNumber= '100' and Fdept= '" + dept + "'");
            }
            datas = api.executeBillQuery(queryParam, Sales.class);
            return ResponseEntity.ok(datas);
        } catch (Exception e) {
            throw new ErpBusinessException(HttpStatus.BAD_REQUEST, ApplicationConstant.KINGDEE_001, e.getMessage());
        }
    }

    /**
     * 物料分类
     *
     * @return
     */
    @GetMapping("/category")
    public ResponseEntity<List<Materials>> getCategories() {
        List<Materials> datas = null;
        try {
            datas = api.executeBillQuery(
                    new QueryParam().
                            setFormId("SAL_MATERIALGROUP").
                            setFieldKeys("FName,FNumber,FID"),
                    //setFilterString("FNumber like '5%' and FNumber!='5'"),
                    Materials.class);//只选择制成品下面的分类
            return ResponseEntity.ok(datas);
        } catch (Exception e) {
            throw new ErpBusinessException(HttpStatus.BAD_REQUEST, ApplicationConstant.KINGDEE_001, e.getMessage());
        }
    }

    @GetMapping("/spec/{fid}")
    public ResponseEntity<List<Materials>> getSpec(@PathVariable String fid) {
        List<Materials> datas = null;
        String filter = "FMATERIALGROUP = " + fid + " and FDOCUMENTSTATUS = 'C' and FUseOrgId=1";//选择一个使用组织
        try {
            datas = api.executeBillQuery(
                    new QueryParam().setFormId("BD_MATERIAL")
                            .setFieldKeys("FMATERIALID ,FName,FNumber,FUseOrgId,FMATERIALGROUP,FDOCUMENTSTATUS,FSpecification,FBaseUnitId.fname,FGROSSWEIGHT,FNETWEIGHT,FWEIGHTUNITID")
                            .setFilterString(filter)
                            .setOrderString("FNumber"), Materials.class);
            return ResponseEntity.ok(datas);
        } catch (Exception e) {
            throw new ErpBusinessException(HttpStatus.BAD_REQUEST, ApplicationConstant.KINGDEE_001, e.getMessage());
        }
    }

    @GetMapping("/wuliu")
    public ResponseEntity<List<Wuliu>> getWuliu() {
        List<Wuliu> datas = null;
        try {
            datas = api.executeBillQuery(
                    new QueryParam().setFormId("BOS_ASSISTANTDATA_DETAIL")  //BAS_ASSISTANTDATAENTRY  辅助资料列表
                            .setFieldKeys("FNUMBER,FDataValue")
                            .setFilterString("FId.FNumber='送货路线'"), Wuliu.class);
            return ResponseEntity.ok(datas);
        } catch (Exception e) {
            throw new ErpBusinessException(HttpStatus.BAD_REQUEST, ApplicationConstant.KINGDEE_001, e.getMessage());
        }
    }

    @GetMapping("/wuliao")
    public ResponseEntity<List<Wuliao>> queryWuliao() {
        String filter = "FUseOrgId=1";
        List<Wuliao> datas = null;
        try {
            datas = api.executeBillQuery(
                    new QueryParam().setFormId("BD_MATERIAL")
                            .setFieldKeys("FMATERIALID ,FName,FNumber,FMATERIALGROUP,FMATERIALGROUP.FName,FMATERIALGROUP.FNumber")
                            .setFilterString(filter)
                            .setOrderString("FNumber"),
                    Wuliao.class);
            return ResponseEntity.ok(datas);
        } catch (Exception e) {
            throw new ErpBusinessException(HttpStatus.BAD_REQUEST, ApplicationConstant.KINGDEE_001, e.getMessage());
        }
    }


    @GetMapping("/shoukuan")
    public ResponseEntity<List<Shoukuan>> getShoukuan() {
        String filter = "FUseOrgId=1 and FDocumentStatus ='C'";
        List<Shoukuan> datas = null;
        try {
            datas = api.executeBillQuery(
                    new QueryParam().setFormId("BD_RecCondition")
                            .setFieldKeys("FNumber,FName")
                            .setFilterString(filter)
                            .setOrderString("FNumber"),
                    Shoukuan.class);
            return ResponseEntity.ok(datas);
        } catch (Exception e) {
            throw new ErpBusinessException(HttpStatus.BAD_REQUEST, ApplicationConstant.KINGDEE_001, e.getMessage());
        }
    }

    @GetMapping("/company")
    public ResponseEntity<List<Company>> getCompany() {
        String filter = "fid.fname='客户所属公司'";
        List<Company> datas = null;
        try {
            datas = api.executeBillQuery(
                    new QueryParam().setFormId("BOS_ASSISTANTDATA_DETAIL")
                            .setFieldKeys("fnumber,fdatavalue")
                            .setFilterString(filter)
                            .setOrderString("fnumber"),
                    Company.class);
            return ResponseEntity.ok(datas);
        } catch (Exception e) {
            throw new ErpBusinessException(HttpStatus.BAD_REQUEST, ApplicationConstant.KINGDEE_001, e.getMessage());
        }
    }
}
